import React from 'react';
import {connect} from 'react-redux'
import {Form, Switch, Table, Button, InputNumber, message, Input, Divider} from "antd/lib/index";
import budgetService from 'containers/budget-setting/budget-organization/budget-item-map/budget-item-map.service'
import {deepFullCopy, messages} from "share/common";
import errorMessage from "share/errorMessage";
import { LanguageInput } from 'components/template';

const FormItem = Form.Item;

class AddBudgetItemMap extends React.Component {
  constructor(props) {
    super(props);
    //初始化对象
    this.state = {
      loading: false,
      data: [],
      dataInit: [],
      columns: [
        {title: messages('budget-setting.key66'/*匹配项编码*/), dataIndex: 'itemCode'},
        {title: messages('budget-setting.key67'/*匹配项名称*/), dataIndex: 'itemName'},
      ],
      selectedRowKeys: [],//默认选中的值
      defaultSelectRowKeys: [],//默认选中的值缓存
      i18n: {}
    };
    //初始化数据获取
    this.getList();
  }

  componentWillReceiveProps(nextProps) {
    console.log('come in');
    if (JSON.stringify(nextProps.info) === JSON.stringify(this.props.info)) {
      return;
    }
    const { priority, groupCode, groupName, enabled } = nextProps.info;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ priority, groupCode, groupName, enabled });
    //state状态改变、回调(此处react重绘严重,注意代码严谨性)
    if (nextProps && nextProps.info && nextProps.info.id) {
      this.setState({
        data: nextProps.info.matchItems,
        i18n: nextProps.info.i18n || {},
        groupName: nextProps.info.groupName
      });
    } else {
      this.setState({ data: this.state.dataInit, i18n: {} });
    }
  }

  //此处页面函数处理（数据获取=》业务处理=》事件操作）
  //star-数据获取
  getList = () => {
    budgetService.getAllMatchItems().then(res => {
      let {data,dataInit, selectedRowKeys} = this.state;
      data = res.data;
      dataInit=res.data;
      data.length > 0 && data.map(item => {
        if (item.checked) {
          selectedRowKeys.push(item.id)
        }
      })
      this.setState({data,dataInit, selectedRowKeys,defaultSelectRowKeys:deepFullCopy(selectedRowKeys)})
    })
  }

  selectedRowsChange = (selectedRowKeys) => {
    this.setState({
      selectedRowKeys
    })
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let {data, selectedRowKeys, i18n, defaultSelectRowKeys} = this.state;
        let formItems = ['groupName', 'groupCode', 'priority', 'enabled'];
        let params = {};
        formItems.map(item => {
          params[item] = values[item]
        })
        params.id = this.props.info.id;
        params.matchItems = [];
        params.i18n = i18n;
        params.organizationId = this.props.orgId;
        selectedRowKeys.length > 0 && selectedRowKeys.map(item => {
          params.matchItems.push(data.filter(i => i.id === item)[0])
        })
        this.setState({loading: true})
        budgetService.addMatchGroups(params)
          .then(res => {
            message.info(params.id ? messages('budget-setting.key68'/*编辑成功*/) : messages('budget-setting.key69'/*添加成功*/));
            this.props.updateAfter(res.data);
            this.props.onClose();
          })
          .catch(e => {
            errorMessage(e.response);
          })
          .finally(() => {
            this.setState({ loading: false, selectedRowKeys: defaultSelectRowKeys });
          });
      }
    })
  }

  handleI18n = (name, value) => {
    const { form: { setFieldsValue } } = this.props;
    let { i18n, groupName } = this.state;
    i18n.groupName = value;
    groupName = name;
    setFieldsValue({ groupName });
    this.setState({ groupName, i18n });
  };

  //end-事件操作
  render() {
    const { loading, columns, data, selectedRowKeys, groupName, i18n } = this.state;
    const {info} = this.props;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 13, offset: 1},
    };
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: this.selectedRowsChange,
      getCheckboxProps: record => ({
        disabled: record.enabled === false,
      })
    }

    return (<div>
      <p className='font-title'>{messages('common.baseInfo')/*基本信息*/}</p>
      <Divider style={{marginTop: 0}}/>
      <Form>
        <FormItem label={messages('budget-setting.key70'/*匹配组编码*/)} {...formItemLayout}>{
          getFieldDecorator('groupCode', {
            rules: [{
              required: true,
              message: messages('common.please.input')/*请输入*/,
            }, {
              max: 20,
              message: messages('budget-setting.key71'/*最多输入20个字符*/),
            }, {
              pattern: /^[0-9A-Za-z_]{0,20}$/,
              message: messages('budget-setting.key72'/*只能输入字母和数字*/)
            }]
          })(
            <Input placeholder={messages('common.please.input')/*请输入*/} style={{width:'50%'}}/>
          )
        }
        </FormItem>
        <FormItem label={messages('budget-setting.key73'/*匹配组名称*/)} {...formItemLayout}>{
          getFieldDecorator('groupName', {
            rules: [{
              required: true,
              message: messages('common.please.input')/*请输入*/,
            }, {
              max: 50,
              message: messages('budget-setting.key74'/*最多输入50个字符*/),
            }]
          })(
            <LanguageInput
              name={groupName}
              isEdit={info.id}
              i18nName={i18n.groupName || null}
              nameChange={this.handleI18n}
              placeholder={messages('common.please.enter')/* 请输入 */}/>
          )
        }
        </FormItem>
        <FormItem label={messages('budget-setting.key75'/*优先级*/)} {...formItemLayout}>{
          getFieldDecorator('priority', {
            message: messages('common.please.input')/*请输入*/,
            rules: [{
              required: true,
              message: messages('common.please.input')/*请输入*/,
            }]
          })(
            <InputNumber
              placeholder={messages('common.please.input')/*请输入*/}
              min={0}
              precision={0}
              max={99999999}
              style={{width: '20%'}}
            />
          )
        }
        </FormItem>
        <FormItem label={messages('common.column.status')/*状态*/} {...formItemLayout}>{
          getFieldDecorator('enabled', {
            valuePropName: 'checked',
            rules:[{
              required: true
            }],
            }
          )(
            <Switch/>
          )
        }
        </FormItem>
      </Form>
      <Divider style={{marginTop: 0}}/>
      <p className='font-title'>{messages('budget-setting.key76'/*创建匹配项*/)}</p>
      <Table columns={columns}
             rowKey='id'
             dataSource={data}
             pagination={false}
             rowSelection={info.id ? undefined : rowSelection}
             bordered
             size="middle"/>
      <div style={{ marginBottom: '30px' }}/>
      <div className="footer-operate" style={{background: 'white',marginLeft:'20px'}}>
        <Button style={{marginLeft: 20}} loading={loading} onClick={this.handleSave} type="primary">{messages('common.save')/*保存*/}</Button>
        <Button style={{marginLeft: 20}} onClick={this.props.onClose}>{messages('common.cancel')/*取消*/}</Button>
      </div>
    </div>)
  }
}

AddBudgetItemMap.propsType = {
  info: React.PropTypes.object,//编辑对象的信息
  updateAfter: React.PropTypes.func, //更新之后的信息
  onClose: React.PropTypes.func, //关闭弹框函数
  orgId: React.PropTypes.string //预算组织ID
}
AddBudgetItemMap.defaultProps = {
  info: {},
  orgId:'',
  onClose: () => {
  },
  updateAfter: () => {
  },
}
AddBudgetItemMap.contextTypes = {
  router: React.PropTypes.object
};


function mapStateToProps(state) {
  return {}
}

const WrappedAddBudgetItemMap = Form.create()(AddBudgetItemMap);

export default connect(mapStateToProps)(WrappedAddBudgetItemMap)
